package com.util;

import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.awt.*;
import java.awt.image.*;
import com.sun.image.codec.jpeg.*;

public class AuthenCodeImage extends HttpServlet {

	private static final long serialVersionUID = 1L;

	private static final String CONTENT_TYPE = "image/jpeg";

	private static final int WIDTH = 40;

	private static final int HEIGHT = 18;

	private static final int LENGTH = 4;

	public static final String SESSION_AUTHEN_CODE = "session_authen_code"; // 设置保存的session对象，用户用户提交时进行匹配的操作。

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setHeader("Pragma", "No-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0);
		response.setContentType(CONTENT_TYPE); // 定义输出的文件格式。
		OutputStream out = response.getOutputStream();
		int width = WIDTH;
		int height = HEIGHT;
		int length = LENGTH;
		String sessionName = request.getParameter("authenName");
		if (sessionName == null) {
			sessionName = SESSION_AUTHEN_CODE;
		}
		try {
			width = Integer.parseInt(request.getParameter("width"));
		} catch (Exception ex) {
			width = WIDTH;
		}
		try {
			height = Integer.parseInt(request.getParameter("heigth"));
		} catch (Exception ex) {
			height = HEIGHT;
		}
		try {
			length = Integer.parseInt(request.getParameter("length"));
		} catch (Exception ex) {
			length = LENGTH;
		}
		// 取得随机整数
		Random ran = new Random(System.currentTimeMillis());
		// 取除第一位后的指定几位
		String seed = (ran.nextInt() + "").substring(1, 1 + length);
		// 将取得的保存在session中
		request.getSession().setAttribute(sessionName, seed);
		// 生成缓冲图象
		BufferedImage image = new BufferedImage(width, height,
				BufferedImage.TYPE_INT_RGB);
		// 取得绘图对象
		Graphics g = image.getGraphics();
		g.setColor(new Color(245, 245, 245));
		// 填充背景色
		g.fillRect(0, 0, width, height);
		// 设置字体颜色
		g.setColor(Color.DARK_GRAY);
		// 设置字体样式
		g.setFont(new Font("Arial", Font.BOLD, 12));
		// 写入指定文字
		g.drawString(seed, 4, 13);
		g.dispose();
		JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
		encoder.encode(image);
		out.close();
	}

}
